﻿using System;
using System.Text;
using System.Windows.Forms;
using PluginInterface;
using SasPlugIn.SASCli;
using SasPlugIn.Table;
using SdmxMl.Structure;
using SdmxMl.Manager;
using Telerik.WinControls.UI;

using SasPlugIn.DB;

namespace SasPlugIn
{
    public partial class UcSasTables : UserControl, IPlugin
    {
        #region Internal Members

        public IomProperties Properties { get; set; }

        private bool isOracleTarget = true;

        private GridManager gridMgr;

        #endregion

        #region Constructor

        public UcSasTables()
        {
            InitializeComponent();
            comboBoxDsdMode.SelectedIndex = 0;
            radPageView1.SelectedPage = radPageView1.Pages[0];

            // fetch default serialized
            Properties = IomProperties.LoadDefault();
            radTextBoxPrefix.Text = Properties.TablePrefix;

            gridMgr = new GridManager(gridView, comboBoxDsdMode, radTextBoxPrefix, ucAnnotationSel);

        }

        #endregion

        #region IPlugin Members

        /// <summary>Event is part of interface but not used </summary>
        public event PluginEvent PluginEventExposed
        {
            add { }
            remove { }
        }

        public void Init(System.Xml.XmlDocument xDoc, object obExtend)
        {
            ;
        }

        public UserControl VisualComponent()
        {
             return this;
        }

        public bool RequiresInit
        {
            get {return false; }
        }

        #endregion

        #region Test Code
        private void test_Click(object sender, EventArgs e)
        {
            try
            {
                // Grid row selected
                if (gridView.CurrentRow != null && gridView.CurrentRow is GridViewDataRowInfo)
                {
                    using (new SdmxMl.Helper.CWaitCursor())
                    {
                        StringBuilder sb = gridMgr.GenerateDbCode(isOracleTarget);
                        if (sb != null)
                        {
                            richTextBoxInfo.Text = sb.ToString();
                            radPageView1.SelectedPage = radPageViewPageInfo;
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }


        private void test_Click2(object sender, EventArgs e)
        {
            if (SdmxMl.Manager.ReferenceManager.TreeSdmx.SelectedNode != null)
            {
                SdmxMl.Common.Artefact a = SdmxMl.Manager.ReferenceManager.TreeSdmx.SelectedNode.Tag as SdmxMl.Common.Artefact;
                try
                {
                    SdmxMl.Manager.SmManager sm = SdmxMl.Manager.ReferenceManager.GetSmContainerImage();
                    if (a != null)
                    {
                        StringBuilder sb = new StringBuilder(1024);
                        sb.Append("PROC SQL;").Append(Environment.NewLine);
                        
                        MaintenableArtefactTable atable = new MaintenableArtefactTable(a, "TableName", radTextBoxPrefix.Text);
                        atable.SasCreateInstructions(sb);
                        atable.SasInsertInstructions(sb);
                        richTextBoxInfo.Text = sb.ToString();
                        sb.Append(Environment.NewLine).Append("run;");

                        KeyFamilyType dsd = a as KeyFamilyType;
                        if (dsd != null)
                        {
                            sb = new StringBuilder(1024);
                            sb.Append("PROC SQL;").Append(Environment.NewLine);
                            DsdTable dsdTable = new DsdTable
                                (dsd, sm, (DsdSasExportMode)comboBoxDsdMode.SelectedIndex, radTextBoxPrefix.Text);
                            dsdTable.SasCreateInstructions(sb);
                            dsdTable.GenerateAssociatedCodelistTables(sb);
                            sb.Append(Environment.NewLine).Append("run;");
                            richTextBoxInfo.Text = sb.ToString();
                        }

                        CodeListType clt = a as CodeListType;
                        if (clt != null)
                        {
                            /*
                            sb = new StringBuilder(1024);
                            sb.Append("PROC SQL;").Append(Environment.NewLine);
                            CodelistArtefactTable cltTable = new CodelistArtefactTable(clt, ucAnnotationSel.AnInventory, "clt", radTextBoxPrefix.Text);
                            cltTable.SasCreateInstructions(sb);
                            cltTable.SasInsertInstructions(sb);
                            sb.Append(Environment.NewLine).Append("run;");
                            */
                            CodelistTable tb = new CodelistTable(clt, null, ucAnnotationSel.AnInventory, "clt", radTextBoxPrefix.Text);
                            TableGenerator gen = new SasTableGenerator(tb);

                            richTextBoxInfo.Text = gen.GenerateTable().ToString();
                        }
                        ConceptSchemeType cs = a as ConceptSchemeType;
                        if (cs != null)
                        {
                            sb = new StringBuilder(1024);
                            sb.Append("PROC SQL;").Append(Environment.NewLine);
                            
                            ConceptSchemeArtefactTable csTable = new ConceptSchemeArtefactTable(cs, null, cs.Id, radTextBoxPrefix.Text);
                            csTable.SasCreateInstructions(sb);
                            csTable.SasInsertInstructions(sb);
                            sb.Append(Environment.NewLine).Append("run;");
                            
                            richTextBoxInfo.Text = sb.ToString();
                        }

                        a = null;
                    }

                    radPageView1.SelectedPage = radPageViewPageInfo;

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        #endregion

        #region Config Events

        private void commandBarButtonConfig_Click(object sender, EventArgs e)
        {
            try
            {
                DlgSasClientConfig aDlg = new DlgSasClientConfig(Properties);
                aDlg.ShowDialog(this);

            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        private void commandBarButtonAdd_Click(object sender, EventArgs e)
        {
            if (ReferenceManager.TreeSdmx.SelectedNode != null)
            {
                try
                {
                    gridMgr.AddMainArtefact(ReferenceManager.TreeSdmx.SelectedNode.Tag as SdmxMl.Common.Artefact,
                        (DsdSasExportMode)comboBoxDsdMode.SelectedIndex, radTextBoxPrefix.Text);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.Message, "SAS Table", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
           }
        }

        #region List File

        private void commandBarButtonLoadCfg_Click(object sender, EventArgs e)
        {
            try
            {
                openDialog.Filter = "List files|*.lst|All Files|*.*";
                if (openDialog.ShowDialog() != DialogResult.OK) return;
                {
                    gridMgr.LoadList(openDialog.FileName);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to load List file: \n" + ex.Message);
            }

        }

        private void commandBarButtonSaveCfg_Click(object sender, EventArgs e)
        {
            try
            {
                saveFileDialog.Filter = "List files|*.lst|All Files|*.*";
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    gridMgr.SaveList(saveFileDialog.FileName);
                }
                    
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to save List file: \n" + ex.Message);
            }

        }

        #endregion

        private void radButtonUpdateAnnotSel_Click(object sender, EventArgs e)
        {
            gridMgr.UpdateSelectedAnnotations(ucAnnotationSel.GetSelectedAnnot());
        }

        private void commandBarButtonTarget_Click(object sender, EventArgs e)
        {
            if (isOracleTarget)
            {
                isOracleTarget = false;
                this.commandBarButtonTarget.Image = global::SasPlugIn.Properties.Resources.sas;
            }
            else
            {
                isOracleTarget = true;
                this.commandBarButtonTarget.Image = global::SasPlugIn.Properties.Resources.oracle;
            }

            // Clear as no more corresponding
            richTextBoxInfo.Text = string.Empty;

        }

        private void commandBarButtonParam_Click(object sender, EventArgs e)
        {
            if (isOracleTarget)
            {
                try
                {
                    gridMgr.EditStarSchemeParameters();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.Message, "Table", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }


    }
}
